<template>
<div class="form-single-fragment" style="position: relative;">
  <header-handle :headerContent="headerContent" :buttons="setHandleButtons()" @goBack="goBack"></header-handle>
  <el-divider class="mt0 mb12"></el-divider>
  <div class="content">
    <el-form ref="groundEdit" :model="formData" class="full-width-input" :rules="rules" label-width="145px" :size="defaultFormItemSize" label-position="right" @submit.native.prevent :disabled="formStatus == 'show'">
      <el-row :gutter="20" style="display: flex; flex-wrap: wrap">
        <el-col :span="12">
          <el-form-item label="阵地名称" prop="groundDto.groundName">
            <el-input class="input-item" v-model="formData.groundDto.groundName" :clearable="true" placeholder="阵地名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否示范站点" prop="groundDto.isExample">
            <el-radio v-model="formData.groundDto.isExample" :label="1">是</el-radio>
            <el-radio v-model="formData.groundDto.isExample" :label="0">否</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="阵地类型" prop="groundDto.groundType">
            <el-select class="input-item" v-model="formData.groundDto.groundType" :clearable="true" filterable placeholder="阵地类型" @change="typeChange" :disabled="initTypeDisabled">
              <el-option v-for="item in initData.groundTypeOptions" :key="item.id" :value="item.id" :label="item.name" :disabled="item.disabled">
                <el-row type="flex" justify="space-between" align="middle">
                  <span>{{item.name}}</span>
                  <el-tag v-if="item.disabled" size="mini" type="info" style="margin-left: 20px;">已禁用</el-tag>
                </el-row>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 所和基地，选所属中心；站选所属中心和所属所 -->
        <el-col :span="12" v-if="formData.groundDto.groundType && formData.groundDto.groundType!= '4'">
          <el-form-item label="所属中心" prop="groundDto.practiceCenter">
            <el-select v-model="formData.groundDto.practiceCenter" :clearable="true" placeholder="所属中心" @change="centerChange" filterable :disabled="formStatus !='add'">
              <el-option v-for="item in initData.centerList" :key="item.groundId" :value="item.groundId" :label="item.groundName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.groundDto.groundType && formData.groundDto.groundType == '3'">
          <el-form-item label="所属所" prop="groundDto.practicePlace">
            <el-select v-model="formData.groundDto.practicePlace" :clearable="true" placeholder="所属所" filterable>
              <el-option v-for="item in placeList" :key="item.groundId" :value="item.groundId" :label="item.groundName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开放时间" prop="groundDto.openTime">
            <el-input class="input-item" v-model="formData.groundDto.openTime" :clearable="true" placeholder="例：周一至周日9：00-17：00" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可容纳人数" prop="groundDto.capacity">
            <el-input-number class="input-item" v-model="formData.groundDto.capacity" :clearable="true" placeholder="可容纳人数" :min="1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区划" prop="groundDto.area">
            <el-cascader class="input-item" v-model="formData.groundDto.area" :options="getAreaList()" clearable :props="getAreaProps()" :disabled="!formData.groundDto.groundType"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细地址" prop="groundDto.address">
            <el-input v-model="formData.groundDto.address" :clearable="true" placeholder="详细地址" class="iptAppendStyle" disabled>
              <template slot="append">
                <el-button @click="checkDetailAddress" :disabled="formStatus == 'show'">选择地址</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="负责人" prop="groundDto.director">
            <el-input class="input-item" v-model="formData.groundDto.director" :clearable="true" placeholder="负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="" prop="groundDto.directorPublic" label-width="0">
            <el-radio v-model="formData.groundDto.directorPublic" :label="1">公开</el-radio>
            <el-radio v-model="formData.groundDto.directorPublic" :label="0">不公开</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="负责人电话" prop="groundDto.directorPhone">
            <el-input class="input-item" v-model="formData.groundDto.directorPhone" :clearable="true" placeholder="负责人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="" prop="groundDto.directorPhonePublic" label-width="0">
            <el-radio v-model="formData.groundDto.directorPhonePublic" :label="1">公开</el-radio>
            <el-radio v-model="formData.groundDto.directorPhonePublic" :label="0">不公开</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="联系人" prop="groundDto.contacts">
            <el-input class="input-item" v-model="formData.groundDto.contacts" :clearable="true" placeholder="联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="" prop="groundDto.contactsPublic" label-width="0">
            <el-radio v-model="formData.groundDto.contactsPublic" :label="1">公开</el-radio>
            <el-radio v-model="formData.groundDto.contactsPublic" :label="0">不公开</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="联系人电话" prop="groundDto.contactsPhone">
            <el-input class="input-item" v-model="formData.groundDto.contactsPhone" :clearable="true" placeholder="联系人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="" prop="groundDto.contactsPhonePublic" label-width="0">
            <el-radio v-model="formData.groundDto.contactsPhonePublic" :label="1">公开</el-radio>
            <el-radio v-model="formData.groundDto.contactsPhonePublic" :label="0">不公开</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="联系电子邮箱" prop="groundDto.email">
            <el-input class="input-item" v-model="formData.groundDto.email" :clearable="true" placeholder="联系邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="" prop="groundDto.emailPublic" label-width="0">
            <el-radio v-model="formData.groundDto.emailPublic" :label="1">公开</el-radio>
            <el-radio v-model="formData.groundDto.emailPublic" :label="0">不公开</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="场所咨询电话" prop="groundDto.tel">
            <el-input class="input-item" v-model="formData.groundDto.tel" :clearable="true" placeholder="咨询电话" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="阵地介绍" prop="groundDto.intro">
            <rich-editor-new :value.sync="formData.groundDto.intro" :readOnly="formStatus == 'show'"></rich-editor-new>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="阵地图片" prop="groundDto.photos">
            <el-upload class="upload-image-item upload-image-multi" name="uploadFile" :headers="getUploadHeaders" :action="getUploadActionUrl('/admin/upms/file/upload')" :data="{ asImage: true}" multiple :on-success="onPictureUrlUploadSuccess"
              :on-remove="onPictureUrlRemoveFile" :before-upload="pictureFile" list-type="picture-card" :file-list="uploadWidgetImpl.fileList" :show-file-list="true" :on-preview="handlePreview">
              <i class="el-icon-plus upload-image-item"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <el-dialog :visible.sync="dialogTableVisible" width="300px">
    <div class="popups" id="qrcode">
      <!-- <vue-qr :text="setQRCodeUrl()" :size="200"></vue-qr> -->
      <img :src="QRImgUrl" />
      <el-button type="text" @click="downQRCode" size="middle" class='downCodeBtn'>下载二维码</el-button>
    </div>
  </el-dialog>
  <BMapAddressSelect ref="bmapAddressSelect" @confirmMapAddress="confirmMapAddress"></BMapAddressSelect>
  <MobileDetail v-if="showMobile" :formData="detailData" @handleClose="closeModal"></MobileDetail>
</div>
</template>

<script>
import {
  findTreeNode,
  findTreeNodePath,
  findItemFromList
} from '@/utils';
import rules from '@/utils/validate.js';
import {
  DropdownWidget,
  TableWidget,
  UploadWidget,
  ChartWidget
} from '@/utils/widget.js';
import MobileDetail from '../H5Show/index.vue'
import {
  uploadMixin,
  statsDateRangeMixin
} from '@/core/mixins';
import {
  GroundController,
  DictionaryController
} from '@/api';
import {
  getToken
} from '@/utils';
import CascaderPlus from '../CascaderPlus/index.vue'
import projectConfig from '@/core/config';
import BMapAddressSelect from '@/components/BMapAddressSelect'
import {
  api as viewerApi
} from 'v-viewer';
// import vueQr from "vue-qr";
import QRCode from "qrcode";
import {
  treeDataTranslate
} from '@/utils';
export default {
  name: 'groundEdit',
  components: {
    CascaderPlus,
    BMapAddressSelect,
    MobileDetail
  },
  mixins: [uploadMixin, statsDateRangeMixin],
  props: {
    initData: {
      type: Object,
      default: () => {
        return {
          organizationList: [],
          groundTypeOptions: [],
          centerList: [],
        }
      }
    },
    formStatus: {
      tyoe: String,
      default: "add"
    },
    initForm: {
      tyoe: Object,
      default: {}
    },
    headerContent: {
      tyoe: String,
      default: ""
    },
    auth: {
      type: String,
      default: ""
    },
    initTypeDisabled: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      areaList: [],
      organizationProps: {
        checkStrictly: true,
        value: 'groundId',
        label: 'groundName',
        emitPath: false
      },
      formData: {
        groundDto: {
          groundId: undefined,
          groundName: undefined,
          groundType: undefined,
          openTime: undefined,
          capacity: undefined,
          address: undefined,
          director: undefined,
          directorPublic: undefined,
          directorPhone: undefined,
          directorPhonePublic: undefined,
          contacts: undefined,
          contactsPublic: undefined,
          contactsPhone: undefined,
          contactsPhonePublic: undefined,
          email: undefined,
          tel: undefined,
          intro: undefined,
          photos: undefined,
          coordinate: undefined,
          province: undefined,
          city: undefined,
          district: undefined,
          status: undefined,
          auditStatus: undefined,
          hold1: undefined,
          hold2: undefined,
          hold3: undefined,
          deleted: undefined,
          createUserId: undefined,
          createTime: undefined,
          updateUserId: undefined,
          updateTime: undefined,
          isDatasourceInit: false
        }
      },
      rules: {
        'groundDto.groundName': [{
          required: true,
          message: '请输入阵地名称',
          trigger: 'blur'
        }],
        'groundDto.groundType': [{
          required: true,
          message: '请选择阵地类型',
          trigger: 'change'
        }],
        'groundDto.practiceCenter': [{
          required: true,
          message: '请选择所属中心',
          trigger: 'change'
        }],
        'groundDto.practicePlace': [{
          required: true,
          message: '请选择所属所',
          trigger: 'change'
        }],
        'groundDto.area': [{
          required: true,
          message: '请选择所属区划',
          trigger: 'change'
        }],
      },
      groundEdit: {
        formFilter: {},
        formFilterCopy: {},
        groundType: {},
        contactsPhonePublic: {
          impl: []
        },
        isInit: false
      },
      closeVisible: 0,
      formCreateCourse: {
        pictureUrl: {
          impl: {}
        }
      },
      uploadWidgetImpl: new UploadWidget(10),
      uploadWidgetImplSpe: new UploadWidget(10),
      dialogVisible: false,
      dialogImageUrl: "",
      dialogImages: [],
      initIndex: 0,
      dialogTableVisible: false,
      cancelBtn: [{
        status: 1,
        label: '取消',
        method: () => {
          this.goBack();
        },
      }, {
        status: 1,
        label: '分享',
        method: () => {
          this.showQRCode();
        },
      }, {
        status: 1,
        label: '预览',
        method: () => {
          this.showMobilePage();
        },
      }],
      placeList: [],
      showMobile: false,
      previewUrl: "",
      QRImgUrl: "",
      detailData: {},
    }
  },
  methods: {
    goBack() {
      this.$emit("goBack")
    },
    initFormData() {
      let me = this;
      me.getAreaList();
      me.getAreaProps()
      //编辑状态下当类型为站时查询当前站所属中心下的所属所
      if (me.initForm.practiceCenter && me.initForm.groundType == '3') {
        me.getPlaceList(me.initForm.practiceCenter)
      }
      me.$set(me.formData, "groundDto", me.initForm)
      me.setPhotos();
      let arr = [];
      arr.push(me.formData.groundDto.province, me.formData.groundDto.city);
      me.formData.groundDto.district ? arr.push(me.formData.groundDto.district) : ''
      me.formData.groundDto.street ? arr.push(me.formData.groundDto.street) : ''
      me.$set(me.formData.groundDto, "area", arr)
    },
    getPlaceList(orgId) {
      let me = this;
      GroundController.list(this, {
        groundDtoFilter: {
          practiceCenter: orgId,
          groundType: '2'
        },
        orderParam: [{
          fieldName: "createTime",
          asc: 0
        }]
      }).then(res => {
        if (res.data.dataList.length > 0) {
          this.placeList = res.data.dataList
        } else {
          this.placeList = [];
        }
      })
    },
    centerChange() {
      let me = this;
      if (me.formData.groundDto.practiceCenter && me.formData.groundDto.groundType == '3') {
        if (me.formData.groundDto.practicePlace) {
          me.$set(me.formData.groundDto, "practicePlace", "")
        }
        this.getPlaceList(me.formData.groundDto.practiceCenter)
      }
    },
    typeChange() {
      let me = this;
      me.$set(me.formData.groundDto, "practicePlace", "")
      let type = me.formData.groundDto.groundType;
      if (type == '4') { //将类型切换为实践中心时，如若存在所属中心则需要清空
        if (me.formData.groundDto.practiceCenter) {
          me.$set(me.formData.groundDto, "practiceCenter", "")
        }
      }
      if (type == '3' && me.formData.groundDto.practiceCenter) { //将类型切换到实践站时需要查询所属所下拉框数据
        me.getPlaceList(me.formData.groundDto.practiceCenter)
      }
    },
    getAreaList() {
      let me = this;
      return me.initData.areaList;
      // let arr = [];
      // let type = me.formData.groundDto.groundType;
      // if (type == '2' || type == '3') {
      //   arr = JSON.parse(sessionStorage.getItem("areaOptions4"))
      // } else {
      //   arr = JSON.parse(sessionStorage.getItem("areaOptions3"))
      // }
      // return arr
    },
    getAreaProps() {
      let me = this;
      let type = me.formData.groundDto.groundType;
      let obj = {
        value: 'code',
        label: 'name',
        checkStrictly: true
      };
      // obj.checkStrictly = type == '1' ? true : false
      return obj
    },
    onPictureUrlUploadSuccess(response, file, fileList) {
      if (response.success) {
        file.downloadUri = response.data.downloadUri;
        file.filename = response.data.filename;
        file.url = URL.createObjectURL(file.raw);
        this.uploadWidgetImpl.onFileChange(file, fileList);
        this.formData.groundDto.photos = this.uploadWidgetImpl.fileList.map(x => x.filename)
        this.fileListToJson(this.uploadWidgetImpl.fileList);
      } else {
        this.$message.error(response.message);
      }
    },
    /**
     * 移除课程图片
     */
    onPictureUrlRemoveFile(file, fileList) {
      this.uploadWidgetImpl.onFileChange(file, fileList);
      this.formData.groundDto.photos = this.uploadWidgetImpl.fileList.map(x => x.filename)
    },
    onPictureUrlUploadSuccessSpe(response, file, fileList) {
      if (response.success) {
        file.downloadUri = response.data.downloadUri;
        file.filename = response.data.filename;
        file.url = URL.createObjectURL(file.raw);
        this.uploadWidgetImplSpe.onFileChange(file, fileList);
        this.formData.groundDto.specialProjectPhotos = this.uploadWidgetImplSpe.fileList.map(x => x.filename)
        this.fileListToJson(this.uploadWidgetImplSpe.fileList);
      } else {
        this.$message.error(response.message);
      }
    },
    /**
     * 移除课程图片
     */
    onPictureUrlRemoveFileSpe(file, fileList) {
      this.uploadWidgetImplSpe.onFileChange(file, fileList);
      this.formData.groundDto.specialProjectPhotos = this.uploadWidgetImplSpe.fileList.map(x => x.filename)
    },
    //图片预览
    handlePreview(val) {
      this.dialogImages = this.formData.groundDto.photos.map(x => {
        return projectConfig.baseUrl + 'admin/upms/file/download?filename=' + x + '&type=1'
      });
      const $viewer = viewerApi({
        images: this.dialogImages
      })
    },
    handleSpePreview(val) {
      this.dialogImages = this.formData.groundDto.specialProjectPhotos.map(x => {
        return projectConfig.baseUrl + 'admin/upms/file/download?filename=' + x + '&type=1'
      });
      const $viewer = viewerApi({
        images: this.dialogImages
      })
    },
    setPhotos() {
      let me = this;
      if (this.formData.groundDto?.photos?.length > 0) {
        let arr = [];
        this.formData.groundDto.photos.forEach((item, i) => {
          this.uploadWidgetImpl.fileList.push({
            filename: item,
            url: projectConfig.baseUrl + 'admin/upms/file/download?filename=' + item
          })
        });
      }
      if (this.formData.groundDto?.specialProjectPhotos?.length > 0) {
        let arr = [];
        this.formData.groundDto.specialProjectPhotos.forEach((item, i) => {
          this.uploadWidgetImplSpe.fileList.push({
            filename: item,
            url: projectConfig.baseUrl + 'admin/upms/file/download?filename=' + item
          })
        });
      }
    },
    setPreviewUrl(item) {
      return projectConfig.baseUrl + 'admin/upms/file/download?filename=' + item + '&type=1'
    },
    setfirst() {
      return this.initData.organizationList
    },
    checkDetailAddress() {
      this.$refs.bmapAddressSelect.show();
    },
    confirmMapAddress(event) {
      let me = this;
      let arr = [event.longitude, event.latitude]
      me.$set(me.formData.groundDto, "coordinate", arr.toString())
      me.$set(me.formData.groundDto, "address", event.address)
    },
    showQRCode() {
      let me = this;
      if (me.formData.groundDto.groundId) {
        let opts = {
          errorCorrectionLevel: "L", //容错级别
          type: "image/png", //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 4, //二维码留白边距
          width: 1280, //宽
          height: 1280, //高
          text: "", //二维码内容
          color: {
            dark: "#666666", //前景色
            light: "#fff", //背景色
          },
        };
        let str = "https://wmsj.1000best.cn/qrcode/ground?groundId=" + me.formData.groundDto.groundId;
        QRCode.toDataURL(str, opts, (err, url) => {
          if (err) throw err;
          me.QRImgUrl = url;
          me.dialogTableVisible = true;
        });
      } else {
        me.$message.warning("暂无详情")
      }
    },
    downQRCode() {
      const fileName = 'ground.png'
      let img = document.getElementById('qrcode').getElementsByTagName('img')[0].src
      let aLink = document.createElement('a')
      let blob = this.base64ToBlob(img)
      let evt = document.createEvent("HTMLEvents")
      evt.initEvent("click", true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob);
      aLink.click()
    },
    base64ToBlob(code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length
      let uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], {
        type: contentType
      })
    },
    setQRCodeUrl() {
      let str =
        "https://wmsj.1000best.cn/qrcode/ground?groundId=" +
        this.formData.groundDto.groundId;
      return str;
    },
    setHandleButtons() {
      let me = this;
      let result = [];
      if (me.formStatus == 'show') {
        result = me.cancelBtn
      } else {
        if (me.auth == 'admin') {
          let arr = [{
            status: 1,
            label: '保存',
            type: 'primary',
            method: () => {
              this.saveData('status', 5);
            },
          }, {
            status: 1,
            label: '保存并校验',
            type: 'primary',
            method: () => {
              this.saveData('hold1', '1');
            },
          }];
          result = me.cancelBtn.concat(arr)
        } else {
          let arr = [{
            status: 1,
            label: '保存',
            type: 'primary',
            method: () => {
              this.saveData('status', 5);
            },
          }, {
            status: 1,
            label: '保存并发布',
            type: 'primary',
            method: () => {
              this.saveData('status', 10);
            },
          }];
          result = me.cancelBtn.concat(arr)
        }
      }
      return result
    },
    dealFormData() {
      let me = this;
      if (me.formData.groundDto.area?.length > 0) {
        let arr = me.formData.groundDto.area;
        me.formData.groundDto.province = arr[0];
        me.formData.groundDto.city = arr[1];
        arr[2] ? me.formData.groundDto.district = arr[2] : '';
        arr[3] ? me.formData.groundDto.street = arr[3] : '';
      }
      return me.formData
    },
    saveData(type, code) {
      let me = this;
      this.$refs.groundEdit.validate((valid) => {
        if (valid) {
          let data = me.dealFormData();
          if (type == 'status') {
            data.groundDto.status = code
          } else {
            data.groundDto.hold1 = code
          }
          if (data.groundDto.groundId) {
            GroundController.update(this, data).then(res => {
              if (res.success) {
                this.$message.success("操作成功");
                this.goBack()
              } else {
                this.$message.error(res.errorMessage);
              }
            }).catch(e => {
              reject(e);
            });
          } else {
            GroundController.add(this, data).then(res => {
              if (res.success) {
                this.$message.success("操作成功");
                this.goBack()
              } else {
                this.$message.error(res.errorMessage);
              }
            }).catch(e => {
              reject(e);
            });
          }
        }
      })
    },
    showMobilePage() {
      let me = this;
      me.detailData = me.formData.groundDto;
      me.showMobile = true
    },
    closeModal() {
      this.showMobile = false
    },
  },
  computed: {},
  mounted() {
    if (Object.values(this.initForm).length > 0) {
      this.initFormData()
    } else {
      this.$set(this.formData, "groundDto", {})
    }
  }
}
</script>

<style type="less" scoped>
.opeareBtn {
  padding: 10px;
  background-color: white;
  text-align: right;
}
</style>
